<template>
  <div class="reports-container">
    <div class="reports-header">
      <h1>报表分析</h1>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateRangeChange"
          style="width: 350px; margin-right: 15px;"
        />
        <el-select v-model="selectedProject" placeholder="选择项目" clearable @change="handleProjectChange" style="width: 200px;">
          <el-option label="全部项目" value="" />
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
      </div>
    </div>

    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <div class="card-icon project-icon">
              <i class="el-icon-folder"></i>
            </div>
            <div class="card-info">
              <div class="card-title">项目总数</div>
              <div class="card-value">{{ statistics.totalProjects }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <div class="card-icon task-icon">
              <i class="el-icon-tickets"></i>
            </div>
            <div class="card-info">
              <div class="card-title">任务总数</div>
              <div class="card-value">{{ statistics.totalTasks }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <div class="card-icon completed-icon">
              <i class="el-icon-check"></i>
            </div>
            <div class="card-info">
              <div class="card-title">已完成任务</div>
              <div class="card-value">{{ statistics.completedTasks }}</div>
              <div class="card-percentage">{{ statistics.completionRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <div class="card-icon overdue-icon">
              <i class="el-icon-time"></i>
            </div>
            <div class="card-info">
              <div class="card-title">逾期任务</div>
              <div class="card-value">{{ statistics.overdueTasks }}</div>
              <div class="card-percentage">{{ statistics.overdueRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>任务状态分布</span>
            </div>
          </template>
          <div class="chart-container" ref="taskStatusChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>任务优先级分布</span>
            </div>
          </template>
          <div class="chart-container" ref="taskPriorityChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>任务完成趋势</span>
            </div>
          </template>
          <div class="chart-container" ref="taskTrendChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>团队成员任务分配</span>
            </div>
          </template>
          <div class="chart-container" ref="memberTaskChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>项目进度对比</span>
            </div>
          </template>
          <div class="chart-container" ref="projectProgressChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
// import { useStore } from 'vuex'
// import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
// 在echarts 5中，不需要单独导入这些组件
// import { PieChart, BarChart, LineChart } from 'echarts/charts'
// import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
// import { CanvasRenderer } from 'echarts/renderers'

// 在echarts 5中，不需要手动注册组件
// echarts.use([
//   TitleComponent,
//   TooltipComponent,
//   LegendComponent,
//   GridComponent,
//   PieChart,
//   BarChart,
//   LineChart,
//   CanvasRenderer
// ])

export default {
  name: 'ReportsView',
  setup() {
    // const store = useStore()
    // const router = useRouter()
    
    // 图表引用
    const taskStatusChart = ref(null)
    const taskPriorityChart = ref(null)
    const taskTrendChart = ref(null)
    const memberTaskChart = ref(null)
    const projectProgressChart = ref(null)
    
    // 图表实例
    let taskStatusChartInstance = null
    let taskPriorityChartInstance = null
    let taskTrendChartInstance = null
    let memberTaskChartInstance = null
    let projectProgressChartInstance = null
    
    // 日期范围和选中的项目
    const dateRange = ref([])
    const selectedProject = ref('')
    
    // 统计数据
    const statistics = reactive({
      totalProjects: 3,
      totalTasks: 10,
      completedTasks: 5,
      completionRate: 50,
      overdueTasks: 2,
      overdueRate: 20
    })
    
    // 模拟项目数据
    const projects = ref([
      {
        id: 1,
        name: '企业官网重构项目'
      },
      {
        id: 2,
        name: '移动应用开发'
      },
      {
        id: 3,
        name: '数据分析平台'
      }
    ])
    
    // 模拟任务数据
    const tasks = ref([
      {
        id: 1,
        name: '需求分析',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '张三',
        priority: '高',
        status: '已完成',
        due_date: '2023-01-25',
        progress: 100,
        create_date: '2023-01-10',
        complete_date: '2023-01-23'
      },
      {
        id: 2,
        name: '设计系统架构',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '李四',
        priority: '高',
        status: '已完成',
        due_date: '2023-02-10',
        progress: 100,
        create_date: '2023-01-26',
        complete_date: '2023-02-08'
      },
      {
        id: 3,
        name: '前端开发',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '王五',
        priority: '中',
        status: '进行中',
        due_date: '2023-03-15',
        progress: 70,
        create_date: '2023-02-11',
        complete_date: null
      },
      {
        id: 4,
        name: '后端开发',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '赵六',
        priority: '中',
        status: '进行中',
        due_date: '2023-03-20',
        progress: 60,
        create_date: '2023-02-11',
        complete_date: null
      },
      {
        id: 5,
        name: '测试',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '钱七',
        priority: '中',
        status: '未开始',
        due_date: '2023-04-10',
        progress: 0,
        create_date: '2023-02-15',
        complete_date: null
      },
      {
        id: 6,
        name: '需求调研',
        project_id: 2,
        project_name: '移动应用开发',
        assignee: '张三',
        priority: '高',
        status: '已完成',
        due_date: '2023-02-10',
        progress: 100,
        create_date: '2023-01-15',
        complete_date: '2023-02-05'
      },
      {
        id: 7,
        name: 'UI设计',
        project_id: 2,
        project_name: '移动应用开发',
        assignee: '王五',
        priority: '高',
        status: '进行中',
        due_date: '2023-03-05',
        progress: 80,
        create_date: '2023-02-11',
        complete_date: null
      },
      {
        id: 8,
        name: '数据库设计',
        project_id: 3,
        project_name: '数据分析平台',
        assignee: '李四',
        priority: '高',
        status: '已完成',
        due_date: '2022-12-15',
        progress: 100,
        create_date: '2022-12-01',
        complete_date: '2022-12-12'
      },
      {
        id: 9,
        name: '数据可视化开发',
        project_id: 3,
        project_name: '数据分析平台',
        assignee: '王五',
        priority: '中',
        status: '已完成',
        due_date: '2023-01-20',
        progress: 100,
        create_date: '2022-12-16',
        complete_date: '2023-01-18'
      },
      {
        id: 10,
        name: '报表功能开发',
        project_id: 3,
        project_name: '数据分析平台',
        assignee: '赵六',
        priority: '中',
        status: '已完成',
        due_date: '2023-02-28',
        progress: 100,
        create_date: '2023-01-21',
        complete_date: '2023-02-25'
      }
    ])
    
    // 处理日期范围变化
    const handleDateRangeChange = () => {
      updateCharts()
    }
    
    // 处理项目选择变化
    const handleProjectChange = () => {
      updateCharts()
    }
    
    // 过滤任务数据
    const getFilteredTasks = () => {
      let filteredTasks = [...tasks.value]
      
      // 按项目过滤
      if (selectedProject.value) {
        filteredTasks = filteredTasks.filter(task => task.project_id === selectedProject.value)
      }
      
      // 按日期范围过滤
      if (dateRange.value && dateRange.value.length === 2) {
        const startDate = new Date(dateRange.value[0])
        const endDate = new Date(dateRange.value[1])
        
        filteredTasks = filteredTasks.filter(task => {
          const createDate = new Date(task.create_date)
          return createDate >= startDate && createDate <= endDate
        })
      }
      
      return filteredTasks
    }
    
    // 更新统计数据
    const updateStatistics = () => {
      const filteredTasks = getFilteredTasks()
      const filteredProjects = new Set(filteredTasks.map(task => task.project_id))
      
      statistics.totalProjects = filteredProjects.size
      statistics.totalTasks = filteredTasks.length
      statistics.completedTasks = filteredTasks.filter(task => task.status === '已完成').length
      statistics.completionRate = statistics.totalTasks > 0 
        ? Math.round((statistics.completedTasks / statistics.totalTasks) * 100) 
        : 0
      
      // 计算逾期任务
      const today = new Date()
      statistics.overdueTasks = filteredTasks.filter(task => {
        const dueDate = new Date(task.due_date)
        return task.status !== '已完成' && dueDate < today
      }).length
      
      statistics.overdueRate = statistics.totalTasks > 0 
        ? Math.round((statistics.overdueTasks / statistics.totalTasks) * 100) 
        : 0
    }
    
    // 初始化任务状态分布图表
    const initTaskStatusChart = () => {
      if (taskStatusChartInstance) {
        taskStatusChartInstance.dispose()
      }
      
      taskStatusChartInstance = echarts.init(taskStatusChart.value)
      
      const filteredTasks = getFilteredTasks()
      const statusCount = {}
      
      filteredTasks.forEach(task => {
        if (!statusCount[task.status]) {
          statusCount[task.status] = 0
        }
        statusCount[task.status]++
      })
      
      const data = Object.keys(statusCount).map(status => ({
        name: status,
        value: statusCount[status]
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: Object.keys(statusCount)
        },
        series: [
          {
            name: '任务状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data,
            color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
          }
        ]
      }
      
      taskStatusChartInstance.setOption(option)
    }
    
    // 初始化任务优先级分布图表
    const initTaskPriorityChart = () => {
      if (taskPriorityChartInstance) {
        taskPriorityChartInstance.dispose()
      }
      
      taskPriorityChartInstance = echarts.init(taskPriorityChart.value)
      
      const filteredTasks = getFilteredTasks()
      const priorityCount = {}
      
      filteredTasks.forEach(task => {
        if (!priorityCount[task.priority]) {
          priorityCount[task.priority] = 0
        }
        priorityCount[task.priority]++
      })
      
      const data = Object.keys(priorityCount).map(priority => ({
        name: priority,
        value: priorityCount[priority]
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: Object.keys(priorityCount)
        },
        series: [
          {
            name: '任务优先级',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data,
            color: ['#67C23A', '#E6A23C', '#F56C6C', '#FF0000']
          }
        ]
      }
      
      taskPriorityChartInstance.setOption(option)
    }
    
    // 初始化任务完成趋势图表
    const initTaskTrendChart = () => {
      if (taskTrendChartInstance) {
        taskTrendChartInstance.dispose()
      }
      
      taskTrendChartInstance = echarts.init(taskTrendChart.value)
      
      const filteredTasks = getFilteredTasks()
      
      // 获取日期范围
      let startDate, endDate
      if (dateRange.value && dateRange.value.length === 2) {
        startDate = new Date(dateRange.value[0])
        endDate = new Date(dateRange.value[1])
      } else {
        // 默认显示最近3个月
        endDate = new Date()
        startDate = new Date()
        startDate.setMonth(startDate.getMonth() - 3)
      }
      
      // 生成日期序列
      const dateList = []
      const currentDate = new Date(startDate)
      while (currentDate <= endDate) {
        dateList.push(new Date(currentDate).toISOString().split('T')[0])
        currentDate.setDate(currentDate.getDate() + 1)
      }
      
      // 计算每天完成的任务数量
      const completedTasksByDate = {}
      dateList.forEach(date => {
        completedTasksByDate[date] = 0
      })
      
      filteredTasks.forEach(task => {
        if (task.complete_date) {
          const completeDate = task.complete_date.split('T')[0]
          if (completedTasksByDate[completeDate] !== undefined) {
            completedTasksByDate[completeDate]++
          }
        }
      })
      
      // 计算累计完成任务数量
      const cumulativeCompletedTasks = []
      let cumulativeCount = 0
      dateList.forEach(date => {
        cumulativeCount += completedTasksByDate[date]
        cumulativeCompletedTasks.push(cumulativeCount)
      })
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['每日完成任务', '累计完成任务']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateList
        },
        yAxis: [
          {
            type: 'value',
            name: '每日完成任务'
          },
          {
            type: 'value',
            name: '累计完成任务'
          }
        ],
        series: [
          {
            name: '每日完成任务',
            type: 'bar',
            data: Object.values(completedTasksByDate)
          },
          {
            name: '累计完成任务',
            type: 'line',
            yAxisIndex: 1,
            data: cumulativeCompletedTasks
          }
        ]
      }
      
      taskTrendChartInstance.setOption(option)
    }
    
    // 初始化团队成员任务分配图表
    const initMemberTaskChart = () => {
      if (memberTaskChartInstance) {
        memberTaskChartInstance.dispose()
      }
      
      memberTaskChartInstance = echarts.init(memberTaskChart.value)
      
      const filteredTasks = getFilteredTasks()
      const memberTaskCount = {}
      
      filteredTasks.forEach(task => {
        if (!memberTaskCount[task.assignee]) {
          memberTaskCount[task.assignee] = {
            total: 0,
            completed: 0
          }
        }
        memberTaskCount[task.assignee].total++
        if (task.status === '已完成') {
          memberTaskCount[task.assignee].completed++
        }
      })
      
      const members = Object.keys(memberTaskCount)
      const totalTasks = members.map(member => memberTaskCount[member].total)
      const completedTasks = members.map(member => memberTaskCount[member].completed)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['总任务数', '已完成任务']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: members
        },
        series: [
          {
            name: '总任务数',
            type: 'bar',
            data: totalTasks
          },
          {
            name: '已完成任务',
            type: 'bar',
            data: completedTasks
          }
        ]
      }
      
      memberTaskChartInstance.setOption(option)
    }
    
    // 初始化项目进度对比图表
    const initProjectProgressChart = () => {
      if (projectProgressChartInstance) {
        projectProgressChartInstance.dispose()
      }
      
      projectProgressChartInstance = echarts.init(projectProgressChart.value)
      
      const filteredTasks = getFilteredTasks()
      const projectProgress = {}
      
      // 计算每个项目的任务总数和已完成任务数
      filteredTasks.forEach(task => {
        if (!projectProgress[task.project_name]) {
          projectProgress[task.project_name] = {
            total: 0,
            completed: 0
          }
        }
        projectProgress[task.project_name].total++
        if (task.status === '已完成') {
          projectProgress[task.project_name].completed++
        }
      })
      
      // 计算项目进度百分比
      const projectNames = Object.keys(projectProgress)
      const progressData = projectNames.map(name => {
        const { total, completed } = projectProgress[name]
        return total > 0 ? Math.round((completed / total) * 100) : 0
      })
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        yAxis: {
          type: 'category',
          data: projectNames
        },
        series: [
          {
            name: '项目进度',
            type: 'bar',
            data: progressData,
            label: {
              show: true,
              position: 'right',
              formatter: '{c}%'
            },
            itemStyle: {
              color: function(params) {
                const value = params.value
                if (value >= 80) return '#67C23A'
                if (value >= 50) return '#E6A23C'
                return '#F56C6C'
              }
            }
          }
        ]
      }
      
      projectProgressChartInstance.setOption(option)
    }
    
    // 更新所有图表
    const updateCharts = () => {
      updateStatistics()
      nextTick(() => {
        initTaskStatusChart()
        initTaskPriorityChart()
        initTaskTrendChart()
        initMemberTaskChart()
        initProjectProgressChart()
      })
    }
    
    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      taskStatusChartInstance && taskStatusChartInstance.resize()
      taskPriorityChartInstance && taskPriorityChartInstance.resize()
      taskTrendChartInstance && taskTrendChartInstance.resize()
      memberTaskChartInstance && memberTaskChartInstance.resize()
      projectProgressChartInstance && projectProgressChartInstance.resize()
    }
    
    onMounted(() => {
      // 设置默认日期范围为最近3个月
      const endDate = new Date()
      const startDate = new Date()
      startDate.setMonth(startDate.getMonth() - 3)
      dateRange.value = [startDate, endDate]
      
      // 初始化图表
      nextTick(() => {
        updateCharts()
        window.addEventListener('resize', handleResize)
      })
    })
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      taskStatusChartInstance && taskStatusChartInstance.dispose()
      taskPriorityChartInstance && taskPriorityChartInstance.dispose()
      taskTrendChartInstance && taskTrendChartInstance.dispose()
      memberTaskChartInstance && memberTaskChartInstance.dispose()
      projectProgressChartInstance && projectProgressChartInstance.dispose()
    })
    
    return {
      dateRange,
      selectedProject,
      projects,
      statistics,
      taskStatusChart,
      taskPriorityChart,
      taskTrendChart,
      memberTaskChart,
      projectProgressChart,
      handleDateRangeChange,
      handleProjectChange
    }
  }
}
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

.reports-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.dashboard-cards {
  margin-bottom: 20px;
}

.dashboard-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.project-icon {
  background-color: #409EFF;
}

.task-icon {
  background-color: #67C23A;
}

.completed-icon {
  background-color: #E6A23C;
}

.overdue-icon {
  background-color: #F56C6C;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-percentage {
  font-size: 14px;
  color: #67C23A;
  margin-top: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
}
</style>